6. Filtered Indexes
For the last example, we
would like to create a filtered index. Assume that the corporate office
exists in territory 4, and you want all of your queries for the VIPs of
the company to be extremely fast. For demonstration purposes, assume
that the director of sales runs a daily report to see the number of
sales and the Totaldue of sales for
his region, and every time that query runs slowly, your boss gets a
phone call. So instead of creating a nonclustered index on the
Territory column, you're going to create a filtered index on the
Territory column just for his area. The code in Listing 6 creates a nonclustered index on TerritoryID and a filtered nonclustered index for territory 4.
Example 6. SQL Script That Creates a Filtered Index
CREATE NONCLUSTERED INDEX ix_Territory ON apWriter.SalesOrderHeader(TerritoryID) INCLUDE (OrderDate,TotalDue)
CREATE NONCLUSTERED INDEX ix_TerritoryFiltered ON apWriter.SalesOrderHeader(TerritoryID) INCLUDE (OrderDate,TotalDue) WHERE TerritoryID = 4
GO
SELECT SalesOrderId, OrderDate,TotalDue FROM apWriter.SalesOrderHeader soh WITH(index(ix_Territory)) WHERE TerritoryID = 4
SELECT SalesOrderId, OrderDate,TotalDue FROM apWriter.SalesOrderHeader soh WITH (index(ix_TerritoryFiltered)) WHERE TerritoryID = 4
|
The listing queries the
SalesOrderHeader table for a particular territory. The execution plan
will show the difference between a filtered index and a nonclustered
index. The execution plan of Listing 6 is shown in Figure 11.
After reviewing the execution plan, you can easily see the benefit of
using filtered indexes instead of just nonclustered indexes.